const categoryMixin = {
  data() {
    return {
      selectedIndex: null,
      drawerMoneyList: [
        "1-50",
        "50-100",
        "100-200",
        "200-300",
        "300-500",
        "500以上",
      ],
      showDrawer: false, // 控制抽屉显示隐藏的状态
      selectName: null, //选中
      customPriceOne: null,
      customPriceTwo: null,
      customStatus: null,
      customValue: null,
      goodsChecked: [],
      sort: null, //"类型：整数；注释： 排序，1-销量  2-价格从高到低  3-价格从低到高"
      isActiveDown: false,
      isActiveUp: false,
      activeTab: null,
      price_start: null, //开始值
      price_end: null, //结束值
      goodsSizeList: {}, //用来传给多规格组件的对象
      logo_list: [], //三级照片logo数组
      hasImageUrl: null, //判断是否有logo的三级分类
      scrollLeft: 0,
      isVisible: false,
      isThree: true,
      animationData: {}, //右侧弹窗动画
      pop_animation: null, //右侧弹窗动画
      bgColor: "rgba(0, 0, 0, 0)",
      hasImageUrl_flag: false,
    };
  },
  watch: {
    hasImageUrl(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.isVisible = true;
        });
      } else {
        this.isVisible = false;
      }
    },
  },

  methods: {
    // 右侧抽屉的开
    openDrawer() {
      this.showDrawer = true;
      // this.bgColor = 'rgba(0, 0, 0, 0)';
      this.$nextTick(() => {
        this.pop_animation = uni.createAnimation({
          duration: 300,
          timingFunction: "ease-out",
        });
        this.pop_animation.translateX(0).step();
        this.animationData = this.pop_animation.export();

        // 背景颜色渐变
        let opacity = 0;
        const bgInterval = setInterval(() => {
          opacity += 0.1;
          // this.bgColor = `rgba(0, 0, 0, ${opacity})`;
          if (opacity >= 0.5) {
            clearInterval(bgInterval);
          }
        }, 30);
      });
    },
    // 右侧抽屉的关
    closeDrawer() {
      this.pop_animation.translateX("100%").step();
      this.animationData = this.pop_animation.export();

      // 背景颜色渐变
      let opacity = 0.5;
      const bgInterval = setInterval(() => {
        opacity -= 0.1;
        // this.bgColor = `rgba(0, 0, 0, ${opacity})`;
        if (opacity <= 0) {
          clearInterval(bgInterval);
          this.showDrawer = false;
        }
      }, 30);
    },
    //库存进度条
    goodsNum(goods_num, more_num) {
      let result = 0;
      if (goods_num > 10) {
        if (more_num === 0) {
          result = 100; // 当more_num为0时，返回100%
        } else {
          result = goods_num / more_num;
          if (result <= 1) {
            result = Math.round(result * 100);
          }
        }
      }

      return result;
    },

    changeColor(val, index) {
      this.customStatus = true;
      this.selectedIndex = index; // 更新被选中项的索引
      this.customColor = val;
    },
    handerlCustom() {
      this.selectedIndex = null;
      this.customStatus = false;
    },
    //tab
    changeTab(val, index, item) {
      this.activeTab = val;
      this.isActiveDown = false;
      this.isActiveUp = false;

      //显示抽屉
      if (val === "0") {
        // this.showDrawer = true;
        this.openDrawer();
        // this.showSelectSku = true
        console.log("显示抽屉");
      }
    },

    // 关闭抽屉
    // closeDrawer() {
    //     this.showDrawer = false;
    //   },

    muchTab(val, index, item) {
      this.activeTab = val;
      if (val === "2") {
        // 如果点击的是价格标签
        if (!this.isActiveUp && !this.isActiveDown) {
          this.isActiveUp = true;
          // console.log('价格排序：从低到高');
          this.sort = 3;
        } else if (this.isActiveUp && !this.isActiveDown) {
          this.isActiveDown = true;
          this.isActiveUp = false;
          this.sort = 2;
          // console.log('价格排序：从高到低');
        } else {
          this.isActiveDown = false;
          this.sort = null;
          // console.log('取消价格排序');
        }
      }
      if (val === "1") {
        // 如果点击的是销量标签
        this.activeTab = val;
        this.isActiveDown = false;
        this.isActiveUp = false;
        this.sort = 1;
        // console.log('销量排序');
      }
      this.chooseThirdCategory(index, item);
    },
    // 点击完成
    handelrComplete(index, item) {
      let selectValue = null;
      !this.customStatus
        ? (selectValue = `${this.customPriceOne ?? 0}-${
            this.customPriceTwo ?? 0
          }`)
        : (selectValue = this.customColor);
      // this.showDrawer = false
      this.closeDrawer();
      this.customValue = selectValue;
      const rangeArray = this.customValue.split("-");

      if (this.customValue === "500以上") {
        this.price_start = parseInt(rangeArray[0]);
        this.price_end = null;
      } else {
        this.price_start = parseInt(rangeArray[0]);
        this.price_end = parseInt(rangeArray[1]);
      }

      if (this.price_start > this.price_end && this.customValue !== "500以上") {
        uni.showToast({
          title: "起始价格不能大于结束价格",
          icon: "none",
        });
        return;
      }

      this.chooseThirdCategory(index, item);
    },

    //重置
    handelrReset() {
      (this.selectedIndex = null),
        (this.customPriceOne = null),
        (this.customPriceTwo = null),
        (this.customStatus = null),
        (this.customValue = null);
    },

    // 加入购物车
    addShopping(goods, index) {
      if (goods.attribute_state == 2) {
        this.$refs.popupComponent.handlerApply();

        goods.skuDetailList.forEach((item) => {
          const goodsNum = parseInt(item.goods_num);
          item.disabled = goodsNum <= 0;
        });
        this.goodsSizeList = goods;
        return;
      }
      console.log(goods, "goods");

      this.$nextTick(async () => {
        if (goods.num > goods.goods_num) return;
        if (goods.goods_num <= 0) {
          return;
        }
        this.animationIndex = index;
        let item = {
          ...this.goodsList[index],
        };
        this.$set(this.goodsList, index, item);
        item.num++;
        if (this.animationIndex === index) {
          const animation = {
            id: Date.now(),
            active: true,
          };
          this.animations.push(animation);
          setTimeout(() => {
            animation.active = false;
            setTimeout(() => {
              this.animations = this.animations.filter(
                (anim) => anim.id !== animation.id
              );
            }, 1000);
          }, 1000);
        }
        const status = await this.$mutations.setShoppingCar({
          id: item.goods_id,
          goods_id: item.id,
          sku_id: item.sku_id,
          num: item.num,
        });

        const existingItem = this.goodsChecked.find(
          (item) => item.goods_id === goods.goods_id
        );
        if (!existingItem) {
          this.goodsChecked.push({
            goods_id: item.id,
          });
        }
        this.$store.checkedList = this.goodsChecked;
        // if (status) {
        //   this.getDataList();
        // }
        // if (status == false) {
        //   item.num--
        // }
      });
    },

    //减少购物车
    reduceShopping(goods, index) {
      this.$nextTick(async () => {
        let item = {
          ...this.goodsList[index],
        };
        this.$set(this.goodsList, index, item);
        item.num--;
        if (item.num === 0) {
          let indexToDelete = this.indexes.indexOf(index);
          if (indexToDelete !== -1) {
            this.indexes.splice(indexToDelete, 1);
          }
        }
        const status = await this.$mutations.setShoppingCar({
          id: item.goods_id,
          goods_id: item.id,
          sku_id: item.sku_id,
          num: item.num,
        });
        // if (status) {
        //   this.getDataList();
        // }
      });
    },

    //右侧的logo图标 公用方法
    //横向自动滚动指定位置
    scrollToPosition(index) {
      this.$nextTick(() => {
        const query = uni.createSelectorQuery().in(this);
        query.select(".category-right-top-box").boundingClientRect();
        query.selectAll(".category-third-item").boundingClientRect();
        query.exec(([scrollViewData, itemsData]) => {
          if (!itemsData || itemsData.length === 0 || !scrollViewData) {
            return;
          }

          const scrollViewWidth = scrollViewData.width;
          const targetItem = itemsData[index];
          if (!targetItem) {
            return;
          }

          let targetScrollLeft;

          if (index === itemsData.length - 1) {
            targetScrollLeft =
              itemsData[itemsData.length - 1].right - scrollViewWidth;
          } else {
            const targetCenter = targetItem.left + targetItem.width / 2;
            const scrollViewCenter = scrollViewWidth / 2;
            targetScrollLeft = targetCenter - scrollViewCenter;
          }

          const maxScroll =
            itemsData[itemsData.length - 1].right - scrollViewWidth;
          targetScrollLeft = Math.max(0, Math.min(targetScrollLeft, maxScroll));

          // 使用 scrollTo 方法进行平滑滚动
          const scrollView = this.$refs.categoryRightTopBox;
          if (scrollView && scrollView.scrollTo) {
            scrollView.scrollTo({
              left: targetScrollLeft,
              behavior: "smooth",
            });
          } else {
            // 如果 scrollTo 不可用，回退到直接设置 scrollLeft
            this.scrollLeft = targetScrollLeft;
          }
        });
      });
    },

    //品牌logo点击事件
    handleClick(index, item) {
      this.activeItem = index; // 点击后高亮当前 item
      this.hasImageUrl = false;
      this.isThree = false;
      this.hasImageUrl_flag = true;
      this.chooseThirdCategory(index, item);
      this.scrollToPosition(index);
    },
    //点击图片样式
    handleTouchStart(index) {
      this.activeItem = index; // 当触摸开始时，设置高亮
    },

    handleTouchEnd() {
      this.activeItem = null; // 当触摸结束时，取消高亮
    },
    // 后退到三级页面
    handlerThree() {
      this.hasImageUrl = true;
      this.isThree = true;
    },
    //二级分类得click
    ClickChooseSecondCategory(index, item) {
      this.isThree = true;
      this.activeItem = null;
      this.scrollLeft = 0;
      if (item?.subset) {
        this.hasImageUrl = item.subset.some(
          (sub) =>
            sub.image_url !== undefined &&
            sub.image_url !== null &&
            sub.image_url !== ""
        );
        this.logo_list = item.subset;
      } else {
        this.hasImageUrl = false;
      }

      if (item) {
        this.label_id = item.id;
        this.label_type = 2;
      }
      if (index >= 0) {
        this.searchForm.person2 = this.secondCategory[index].id;
        this.thirdCategory = this.secondCategory[index].subset
          ? this.secondCategory[index].subset
          : [];
      } else {
        this.searchForm.person2 = "";
        this.thirdCategory = [];
      }
      this.chooseThirdCategory(this.thirdCategory.length ? 0 : -1);
    },
  },
};

export default categoryMixin;
